package 线程;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.LongStream;

import org.junit.Test;

public class 多线程搜索 {
    private AtomicInteger counter = new AtomicInteger(-1);
    private List<Future<Integer>> result = new ArrayList<>();

    public int find(List list, Object v, final Integer threadNum) {
        ExecutorService ex = Executors.newFixedThreadPool(threadNum);
        if (list.isEmpty() || v == null) return -1;
        int k = list.size() / threadNum;
        for (int i = 0; i < threadNum; i++) {
            final int ftem = i;
            Future<Integer> res = ex.submit(() -> get(list, v, ftem * k, (ftem + 1) * k));
            result.add(res);
        }
        for (int i = 0; i < result.size(); i++) {
            Integer res = -1;
            try {
                res = result.get(i).get();
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
            if (res != -1) return res;
        }
        return -1;
    }

    private <T> int get(List<T> list, T t, int start, int end) {
        for (int i = start; i < end; i++) {
            if (Objects.equals(t, list.get(i)) && counter.compareAndSet(-1, 1)) {
                return i;
            }
        }
        return -1;
    }

    @Test
    public void test01() {
        多线程搜索 t = new 多线程搜索();
        int k = 10000000;
        List<Long> larr = new ArrayList<Long>();
        for (int i = 0; i < k; i++) {
            larr.add((long) i);
        }
        System.out.println("数据准备完毕。准备计算");
        long statrTime = System.currentTimeMillis();
        int res = t.find(larr, 9999999L, 1);
        //int res=get(larr,9999999L);
        System.out.println((System.currentTimeMillis() - statrTime) + ":" + res);
    }

    public int get(List list, Object v) {
        for (int i = 0; i < list.size(); i++) {
            if (Objects.equals(v, list.get(i))) {
                return i;
            }
        }
        return -1;
    }
}
